import java.util.HashMap;
import java.util.Map;

class Solution {
    public int findMaxLength(int[] nums) {
        int sum = 0;
        Map<Integer,Integer> map = new HashMap<>();
        //和为0子数组前的和为sum-0的子数组
        map.put(0,-1);
        int max = 0;
        for (int i = 0; i < nums.length; i++) {
            //将为 0 -> -1
            //数组和为k -> 数组和为0
            sum += nums[i] == 0 ? -1 : 1;
            if (map.containsKey(sum)) {
                max = Math.max(max,i - (map.get(sum) + 1) + 1);
            }else {
                map.put(sum,i);
            }
        }
        return max;
    }
}